qui(
    function(require, exports, module) {

        Vodad.Grid = function(options) {
            this.dao = Vodad.Dao;
            this.config = Vodad.Config;
            this.util = Vodad.Util;
            this.options = options || {};
			//this.channel_id = Com.url.getQueryValue("channel_id",location.href);
			//this.channel_name = Com.url.getQueryValue("channel_name",location.href);
            this.construct = options.construct || function() {
                this.init();
            };
            this.construct.call(this);
        };

        Com.inherits(Vodad.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.initDialog();
                self.bindBasicEvent();
                self.initSuggest();
            },


            bindBasicEvent: function() {
                var self = this;

                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                $form.find('input[name="GET_opTime"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="GET_opTime"]').timepicker("option", selectedDate);
                    }
                });
                $form.find('input[name="LET_opTime"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="LET_opTime"]').timepicker("option", selectedDate);
                    }
                });
                $container.find('.query-add-vod').click(function() {
                    $("#dlg_upload_video").dialog("open");
                });

                 $container.find('.query-add-image').click(function() {
                    $("#dlg_upload_image").dialog("open");
                });

                $container.find('.query-btn').on('click.query', function() {
                    self.query();
                    return false;
                });

                $('.uploadBtnVideo').bind("change", function (e) {
                    e.preventDefault();
                    var $containerVideo = $("#dlg_upload_video");
                    $containerVideo.find('input[name="opTime"]').val(new Date().format("yyyy-MM-dd hh:mm:ss"));
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file);

                    var params = {};
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    if (params.file_size > 15 * 1024 * 1024 * 1024) {
                        EpgWeb.Plugin.showTips({content: "上传视频大小不允许超过15G, 请重新上传", type: "error"});
                        return;
                    }
                    if (!Vodad.Util.isValidVideo(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "暂时不支持该格式文件上传，请重新选择素材", type: "error"});
                        return;
                    }

                    Vodad.Util.startUploadVideo(params, self.uploadVideoFun);
                });

                $('.uploadBtnVideoImage').bind("change", function (e) {
                    var $containerVideo = $("#dlg_upload_video");
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file);

                    var params = self.config.EffectUploadCommonParams;

                    params.business_type = "image";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    if (params.file_size > 3 * 1024 *1024) {
                        EpgWeb.Plugin.showTips({content: "上传封面图大小不允许超过3M, 请重新上传", type: "error"});
                        return;
                    }
                    if (!Vodad.Util.isValidImage(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传封面图格式只支持jpg|png, 请重新上传", type: "error"});
                        return;
                    }

                    Vodad.Util.startUploadFile(params, self.uploadPicFun);

                });

                $('.uploadBtnImage').bind("change", function (e) {
                    var $containerImage = $("#dlg_upload_image");
                    $containerImage.find('input[name="opTime"]').val(new Date().format("yyyy-MM-dd hh:mm:ss"));
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file);

                    var params = self.config.EffectUploadCommonParams;

                    params.business_type = "image";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    if (params.file_size > 20 * 1024 *1024) {
                        EpgWeb.Plugin.showTips({content: "上传图片大小不允许超过20M, 请重新上传", type: "error"});
                        return;
                    }
                    if (!Vodad.Util.isValidImage(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传图片格式不支持, 请重新上传", type: "error"});
                        return;
                    }

                    Vodad.Util.startUploadFile(params, self.uploadImageFun);

                });
			},

			initDialog: function () {
			    var self = this;
			    $("#dlg_upload_video").dialog({
                     title: "上传视频",
                     autoOpen: false,
                     width: 680,
                     height: 450,
                     modal: true,
                     resizable: false,
                     buttons: [
                         {
                             text: "确定",
                             click: function () {
                                var data = {};
                                var $containerVideo = $("#dlg_upload_video");
                                data["name"] = $containerVideo.find('input[name="name"]').val();
                                data["fileType"] = $containerVideo.find('input[name="fileType"]').val();
                                data["fileSize"] = $containerVideo.find('input[name="fileSize"]').val();
                                data["address"] = $containerVideo.find('input[name="address"]').val();
                                data["picAddress"] = $containerVideo.find('input[name="picAddress"]').val();
                                data["opTime"] = $containerVideo.find('input[name="opTime"]').val();
                                data["opUser"] = $("div.user a.name").html();
                                data["contentType"] = $containerVideo.find('select[name="contentType"]').val();
                                data["duration"] = $containerVideo.find('input[name="duration"]').val();
                                data["remark"] = $containerVideo.find('input[name="remark"]').val();
                                data["type"] = 0;
                                if (!Vodad.Util.verifyForm(data, data.type)) {
                                    return;
                                }
                                Vodad.Dao.add({"data": JSON.stringify(data)}, function(data) {
                                    if (data != null && data.code == "A00000") {
                                        $('.query-btn').click();
                                        var $containerVideo = $("#dlg_upload_video");
                                        $containerVideo.find('input[name="name"]').val("");
                                        $containerVideo.find('input[name="fileType"]').val("");
                                        $containerVideo.find('input[name="fileSize"]').val("");
                                        $containerVideo.find('input[name="address"]').val("");
                                        $containerVideo.find('input[name="picAddress"]').val("");
                                        $containerVideo.find('input[name="opTime"]').val("");
                                        $containerVideo.find('select[name="contentType"]').val(1);
                                        $containerVideo.find('input[name="duration"]').val("");
                                        $containerVideo.find('input[name="remark"]').val("");
                                        $containerVideo.dialog("close");
                                        console.log("VODAD save successed !");
                                    }
                                });
                             }
                         },
                         {
                             text: "取消",
                             click: function () {
                                var $containerVideo = $("#dlg_upload_video");
                                $containerVideo.find('input[name="name"]').val("");
                                $containerVideo.find('input[name="fileType"]').val("");
                                $containerVideo.find('input[name="fileSize"]').val("");
                                $containerVideo.find('input[name="address"]').val("");
                                $containerVideo.find('input[name="picAddress"]').val("");
                                $containerVideo.find('input[name="opTime"]').val("");
                                $containerVideo.find('select[name="contentType"]').val(1);
                                $containerVideo.find('input[name="duration"]').val("");
                                $containerVideo.find('input[name="remark"]').val("");
                                $(this).dialog("close");
                             }
                         }
                     ]
                 });
                 $("#dlg_upload_image").dialog({
                      title: "上传图片",
                      autoOpen: false,
                      width: 680,
                      height: 450,
                      modal: true,
                      resizable: false,
                      buttons: [
                          {
                              text: "确定",
                              click: function () {
                                var data = {};
                                var $containerImage = $("#dlg_upload_image");
                                data["name"] = $containerImage.find('input[name="name"]').val();
                                data["fileType"] = $containerImage.find('input[name="fileType"]').val();
                                data["fileSize"] = $containerImage.find('input[name="fileSize"]').val();
                                data["picAddress"] = $containerImage.find('input[name="picAddress"]').val();
                                data["opTime"] = $containerImage.find('input[name="opTime"]').val();
                                data["opUser"] = $("div.user a.name").html();
                                data["contentType"] = $containerImage.find('select[name="contentType"]').val();
                                data["remark"] = $containerImage.find('input[name="remark"]').val();
                                data["type"] = 1;
                                if (!Vodad.Util.verifyForm(data, data.type)) {
                                    return;
                                }
                                Vodad.Dao.add({"data": JSON.stringify(data)}, function(data) {
                                  if (data != null && data.code == "A00000") {
                                      $('.query-btn').click();
                                      var $containerImage = $("#dlg_upload_image");
                                      $containerImage.find('input[name="name"]').val("");
                                      $containerImage.find('input[name="fileType"]').val("");
                                      $containerImage.find('input[name="fileSize"]').val("");
                                      $containerImage.find('input[name="picAddress"]').val("");
                                      $containerImage.find('input[name="opTime"]').val("");
                                      $containerImage.find('select[name="contentType"]').val(1);
                                      $containerImage.find('input[name="remark"]').val("");
                                      $containerImage.dialog("close");
                                      console.log("VODAD save successed !");
                                  }
                                });
                              }
                          },
                          {
                              text: "取消",
                              click: function () {
                                var $containerImage = $("#dlg_upload_image");
                                $containerImage.find('input[name="name"]').val("");
                                $containerImage.find('input[name="fileType"]').val("");
                                $containerImage.find('input[name="fileSize"]').val("");
                                $containerImage.find('input[name="picAddress"]').val("");
                                $containerImage.find('input[name="opTime"]').val("");
                                $containerImage.find('select[name="contentType"]').val(1);
                                $containerImage.find('input[name="remark"]').val();
                                $(this).dialog("close");
                              }
                          }
                      ]
                  });

                $("#dlg_upload_waiting").dialog({
                    autoOpen: false,
                    width: 300,
                    height: 150,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,

                });

                $("#dlg_upload_progress").dialog({
                    autoOpen: false,
                    width: 450,
                    height: 150,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                });
                 $("div.ui-dialog-buttonset").find("button:eq(0)").addClass("btn btn-primary");
                 $("div.ui-dialog-buttonset").find("button:eq(1)").addClass("btn");
			},

			bindFormEvent: function($form) {
                var self = this;

			},

            run: function(options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig();
                options = $.extend(true, {
                    width: 1700,
                   // multiselect: true,
                    //multiselectWidth: 30,
                    shrinkToFit: false,
                    // idPrefix: 'Video-',
                    autowidth: false
                }, gridConfig, options);
                self.$grid.jqGrid(options);

              //  self.initGrid.call(this, options, callback);
                self.$grid.jqGrid('setGridParam', {
                    postData: {},
                }).trigger('reloadGrid', [{
                    page: 1
                }]);
            },

            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function(item) {
					return true;
                });

				var checkboxVal = [];
                var name,type;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    type = this.nodeName;
                    if (name) {
                        if (type=='SELECT') {
                            if ($(this).val() != "all") {
                                params[name] = $.trim($(this).val());
                            }
                        } else {
                            if($(this).val()){
                                params[name] = $.trim($(this).val());
                            }
                        }
                    }
                });
                return params;
            },

            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var data = self.getParam();
                var checkArr = [];
                if (data.GET_opTime != null) {
                    checkArr.push({value: data.GET_opTime, error: "上传开始时间格式错误", type: "date"});
                }
                if (data.LET_opTime != null) {
                    checkArr.push({value: data.LET_opTime, error: "上传结束时间格式错误", type: "date"});
                }
                if (checkArr.length > 0) {
                    if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                        return false;
                    }
                }
                var params = {"paramsObj": JSON.stringify(data)};
                var checkArr = [];

                $grid.jqGrid('setGridParam', {
                    postData: params,
                }).trigger('reloadGrid', [{
                    page: 1
                }]);
            },

            uploadVideoFun: function (data, params) {
                var self = this;
                var $containerVideo = $("#dlg_upload_video");
                var name = params.file.name;
                $containerVideo.find('input[name="name"]').val(name.substring(0, name.lastIndexOf(".")));
                $containerVideo.find('input[name="fileType"]').val(params.file_type);
                $containerVideo.find('input[name="fileSize"]').val(params.file_size);
                $containerVideo.find('input[name="address"]').val(Vodad.Config.UPLOAD_VIDEO_PARAMS.url + data.uuid);
            },
            uploadPicFun: function (data, params) {
                var self = this;
                var $containerVideo = $("#dlg_upload_video");
                $containerVideo.find('input[name="picAddress"]').val(data.httpInnerUrl);
            },
            uploadImageFun: function (data, params) {
                var self = this;
                var $containerImage = $("#dlg_upload_image");
                var name = params.file.name;
                $containerImage.find('input[name="name"]').val(name.substring(0, name.lastIndexOf(".")));
                $containerImage.find('input[name="fileType"]').val(params.file_type);
                $containerImage.find('input[name="fileSize"]').val(params.file_size);
                $containerImage.find('input[name="picAddress"]').val(data.httpInnerUrl);
            },
            initSuggest: function () {
                var emailSuggest = {
                    options: {
                        source: "/api/redirect",
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: "http://lego.iqiyi.com/external/auth/auth-api/services/user/search", type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["userName"];
                                itemData[options.labelKey] = item["email"];
                                itemData["value"] = item["userName"]
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.id + "(" + item.label + ")";
                        }
                    }
                }
                $("input[name=EQS_opUser]").suggest(emailSuggest.options);

                var nameSuggest = {
                    options: {
                        source: "/api/vod/ad/getList",
                        method: "post",
                        multiple: false,
                        clearInvalid: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {LIKES_name: term};
                            return {"paramsObj": JSON.stringify(requestData)}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data.result == null ? null : json.data.result;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["name"];
                                itemData[options.labelKey] = item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }
                $("input[name=LIKES_name]").suggest(nameSuggest.options);
            },
        });

    }
);